package com.shop.front.shiro;

import com.shop.domain.user.User;
import com.shop.front.dao.user.UserDao;
import com.shop.web.shiro.token.BaseUsernamePasswordToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 前台系统身份认证
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    /**
     * 权限授权，即赋予当前登录用户已配置好的权限，以供shiro校验
     * <p>
     *     前台系统不需要做权限控制
     * </p>
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 身份授权，即获取当前登录人的账密信息，以供Shiro校验
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        BaseUsernamePasswordToken token = (BaseUsernamePasswordToken) authenticationToken;
        String name = (String) token.getPrincipal();
        User user = userDao.findUserByMobileOrName(name);
        if(null == user) {
            throw new UnknownAccountException();
        }

        //if(user.getLockType() > 0) {    // 账户锁定
        //   throw new LockedAccountException();
        //}

        // 密码加密使用固定盐值
        return new SimpleAuthenticationInfo(user, user.getPwd(), UserShiroUtil.byteSource(UserShiroUtil.ENCRYPT_FIXED_SALT), getName());
    }

}
